package com.hyperchain.service.Impl;

import cn.hutool.extra.template.TemplateEngine;
import com.hyperchain.config.EmailConfig;
import com.hyperchain.entity.dto.MailDto;
import com.hyperchain.service.EmailService;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;

@Service
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {

    private final EmailConfig emailConfig;

    private final JavaMailSender mailSender;

    @Value("{spring.email.nickName}")
    private String nickName;

    public static void main(String[] args) throws Exception {
        File tempFile = File.createTempFile("s2jinbyf", ".png");
        URL url = new URL("https://iprp.zjip.org.cn/ddd766863e357a534b4031cbfb8f10e4d2076e269a1a092eb4ace49c822b3f49.png");
        InputStream inputStream = url.openStream();
        tempFile.deleteOnExit();
        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            IOUtils.copy(inputStream, out);
        }
        System.out.println(tempFile.exists());
    }

    @Override
    public void sendEmail(String receiverName, String title, String content , String path) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message,true);
            helper.setFrom("2535385543@qq.com");

            helper.setTo(receiverName);
            helper.setSubject("转账凭证");
            MailDto mailDto = new MailDto();
            mailDto.setUserName("rr");
            mailDto.setEmail("123");
            mailDto.setPhone("123");
            mailDto.setProofMsg("123");
            mailDto.setRemark(null);
            helper.setText(mailDto.toString() , true);
            helper.addAttachment("附件.jpg", createFile(path));
        }catch (Exception e){
            e.printStackTrace();
        }
        mailSender.send(message);
    }

    private File createFile(String path) throws Exception{
        File tempFile = File.createTempFile("s2jinbyf", ".png");
        URL url = new URL(path);
        InputStream inputStream = url.openStream();
        tempFile.deleteOnExit();
        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            IOUtils.copy(inputStream, out);
        }
        return tempFile;
    }
}
